package com.liuwei.msmall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liuwei.msmall.common.constant.OrderConstant;
import com.liuwei.msmall.common.dto.MemberRespDTO;
import com.liuwei.msmall.common.dto.SkuInfoWithSaleAttrDTO;
import com.liuwei.msmall.common.dto.mq.OrderTo;
import com.liuwei.msmall.common.dto.mq.SeckillOrderTo;
import com.liuwei.msmall.common.enums.OrderStatusEnum;
import com.liuwei.msmall.common.exception.NoStockException;
import com.liuwei.msmall.common.utils.DateUtils;
import com.liuwei.msmall.common.utils.PageUtils;
import com.liuwei.msmall.common.utils.Query;
import com.liuwei.msmall.common.utils.R;
import com.liuwei.msmall.order.dao.OrderDao;
import com.liuwei.msmall.order.entity.OrderEntity;
import com.liuwei.msmall.order.entity.OrderItemEntity;
import com.liuwei.msmall.order.feign.CartFeignService;
import com.liuwei.msmall.order.feign.MemberFeignService;
import com.liuwei.msmall.order.feign.ProductFeignService;
import com.liuwei.msmall.order.feign.WareFeignService;
import com.liuwei.msmall.order.interceptor.OrderInterceptor;
import com.liuwei.msmall.order.service.OrderItemService;
import com.liuwei.msmall.order.service.OrderService;
import com.liuwei.msmall.order.service.PaymentInfoService;
import com.liuwei.msmall.order.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {


    private ThreadLocal<OrderSubmitVo> submitVoThreadLocal=new ThreadLocal<>();

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    OrderItemService orderItemService;


    @Autowired
    PaymentInfoService paymentInfoService;


    @Autowired
    ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    RabbitTemplate rabbitTemplate;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    public OrderConfirmVo getOrderConfirmData() throws ExecutionException, InterruptedException {

        MemberRespDTO memberRespVo = OrderInterceptor.loginUserLocal.get();
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        System.out.println("主线程id:"+Thread.currentThread().getId());
        //由于开启了异步线程执行任务，不能共享主线程中的Fegin的RequestInterceptor数据
        //获取原来线程中的数据，不在同一个线程，RequestContextHolder会丢失上下文
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        //开启异步编排任务执行
        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            System.out.println("getAddressFuture线程的id:"+Thread.currentThread().getId());
            //执行远程调用之前先将数据重新放到线程中
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //出现的问题:在RequestInterceptor拦截器的时候获取不到feign的共享数据
            //调用远程服务查出用户收货地址
            List<UserAddressVo> addressVos = memberFeignService.getReceiveAddress(memberRespVo.getId());
            addressVos.stream().map(item->{
                String phone = item.getPhone();
                //将电话号码进行加密
                item.setPhone(phone);
                return item;
            }).collect(Collectors.toList());
            orderConfirmVo.setAddressVos(addressVos);
        }, threadPoolExecutor);

        CompletableFuture<Void> getUserCartItemFuture = CompletableFuture.runAsync(() -> {
            System.out.println("getUserCartItemFuture线程的id:"+Thread.currentThread().getId());
            //调用之前将老请求中的数据放到新线程中
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //调用远程服务查出用户的购物项
            List<OrderConfirmItemVo> userCartItem = cartFeignService.getCurrentUserCartItem();
            orderConfirmVo.setItems(userCartItem);
        }, threadPoolExecutor);

        //设置用户积分
        orderConfirmVo.setIntegration(memberRespVo.getIntegration());
        //总金额，应付金额自动计算。。

        //等待所有任务执行完
        CompletableFuture.allOf(getAddressFuture,getUserCartItemFuture).get();

        //TODO 接口幂等性，防止应为网络闪断导致用户多次重复提交订单信息
        //设置token令牌
        String token= UUID.randomUUID().toString().replace("-","");
        //在redis服务器上存一份
        redisTemplate.opsForValue().set(OrderConstant.ORDER_TOKEN_PREFIX+memberRespVo.getId(),token,30, TimeUnit.MINUTES);
        //在客户端也设置一份
        orderConfirmVo.setToken(token);
        return orderConfirmVo;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public OrderSubmitRespVo submitOrder(OrderSubmitVo vo) {
        //1.验证令牌，2.创建订单，3.验价，4.锁库存。。。。
        //将提交的订单数据放到线程共享数据中
        submitVoThreadLocal.set(vo);
        OrderSubmitRespVo submitRespVo = new OrderSubmitRespVo();
        submitRespVo.setCode(0L);//如果在创建订单的过程中没有出现异常，则code为0
        String orderToken = vo.getOrderToken();
        //TODO 1.验证令牌,对比令牌,从redis中获取令牌，删除令牌此过程必须是原子操作
       Long result = checkToken(orderToken);
        if (result == 0L){
            //令牌验证失败
            submitRespVo.setCode(1L);
            return submitRespVo;
        }
        //令牌验证成功
        //TODO 2.创建订单
        OrderCreateVo orderCreateVo = createOrder();
        //3.验价，验证前台传来的价格和后台重新计算的价格是否相等
        double abs = Math.abs(orderCreateVo.getOrder().getPayAmount().subtract(vo.getPayPrice()).doubleValue());
        if (abs<0.01){
            //验价成功，价格无变化
            //保存订单
            saveOrder(orderCreateVo);
            //TODO 3.锁定库存
            R res = lockStock(orderCreateVo);
            //拿到每个商品的锁定库存结果
            if (res.getCode()==0){
                //锁定库存成功
                //TODO 4.扣减用户积分,模拟异常，发现锁定库存不能回滚
                //给mq发送消息,已经创建好的订单
                try {
                    log.info("库存锁定成功，给mq发送消息,已经创建好的订单时间：{}", LocalDateTime.now());
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",orderCreateVo.getOrder());
                }catch (Exception e){
                    //TODO 可能由于网络原因发送失败，将消息记录到数据库中，之后在定期扫描发送失败的消息，重新发送
                    log.error("发送创建订单成功消息失败,{}",e);
                }
                log.info("消息发送成功,时间：{}",LocalDateTime.now());
                submitRespVo.setOrderEntity(orderCreateVo.getOrder());
                return submitRespVo;
            }else {
                //锁定库存失败，回滚创建订单，，，
                submitRespVo.setCode(3L);
                throw new NoStockException();
            }

        }else {
            //验价失败，说明价格有变化，提示用户
            submitRespVo.setCode(2L);//验价失败
            return submitRespVo;
        }
    }

    private Long checkToken(String orderToken) {

        //获取当前用户信息
        MemberRespDTO memberRespVo = OrderInterceptor.loginUserLocal.get();

        //原子验证令牌，使用redis的lua脚本保证此过程是原子性的
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        //执行脚本并拿到返回结果冲，过程中出现任何错误都返回0
        //0令牌失败   1删除成功
        Long result = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Arrays.asList(OrderConstant.ORDER_TOKEN_PREFIX + memberRespVo.getId()), orderToken);

        return result;
    }

    private R lockStock(OrderCreateVo orderCreateVo) {
        LockStockVo lockStockVo = new LockStockVo();
        lockStockVo.setOrderSn(orderCreateVo.getOrder().getOrderSn());
        List<OrderConfirmItemVo> collect = orderCreateVo.getOrderItems().stream().map(item -> {
            OrderConfirmItemVo confirmItemVo = new OrderConfirmItemVo();
            confirmItemVo.setSkuId(item.getSkuId());//设置skuid
            confirmItemVo.setSkuTitle(item.getSkuName());//设置sku名称
            confirmItemVo.setCountNum(item.getSkuQuantity());//设置sku数量
            confirmItemVo.setSkuPrice(item.getSkuPrice());
            return confirmItemVo;
        }).collect(Collectors.toList());
        lockStockVo.setLockItems(collect);
        //todo 远程调用锁库存 容易出现假失败（网络故障导致fegin调用超时），
        //解决办法：使用库存的自动解锁逻辑
        R lockOrderStockResp = wareFeignService.lockOrderStock(lockStockVo);

        return lockOrderStockResp;
    }

    @Override
    public void orderClose(OrderEntity orderEntity) {
        //先查询订单最新状态
        OrderEntity newOrder = this.getById(orderEntity.getId());

        //如果时间到了，判断订单状态还是未支付状态，则关闭订单
        if (newOrder.getStatus()==OrderStatusEnum.CREATE_NEW.getCode()){
            OrderEntity update = new OrderEntity();
            update.setId(orderEntity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            //发送消息，主动告诉库存解锁，防止订单消息的过期时间晚于库存解锁消息的过期时间
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(newOrder,orderTo);
            //TODO 防止网络故障，消息丢失，创建数据库记录每条消息，定期扫描数据据库，如果有发送失败的消息重新发送
            try {
                log.info("开始订单主动推送库存解锁消息。。。。");
                //String exchange, String routingKey, Object message
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
            }catch (Exception e){
                //出现网络原因发送消息未成功
                log.error("订单主动推送库存解锁消息失败：{}",e);
            }

        }
    }

    @Override
    public List<OrderListVo> getOrderList(Integer status) {


        MemberRespDTO member = OrderInterceptor.loginUserLocal.get();

        List<OrderEntity> orderEntities = this.list(new LambdaQueryWrapper<OrderEntity>()
                .eq(OrderEntity::getMemberId, member.getId()).eq(status!=-1,OrderEntity::getStatus,status)
                .orderByDesc(OrderEntity::getCreateTime));

        if (!CollectionUtils.isEmpty(orderEntities)){

            List<OrderListVo> orderListVos= orderEntities.stream().map(item -> {
                OrderListVo listVo = new OrderListVo();
                listVo.setOrder(item);
                List<OrderItemEntity> list = orderItemService.list(new LambdaQueryWrapper<OrderItemEntity>().eq(OrderItemEntity::getOrderSn, item.getOrderSn()));
                listVo.setOrderItems(list);
                return listVo;
            }).collect(Collectors.toList());

            return orderListVos;

        }
        return null;
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        return this.getOne(new LambdaQueryWrapper<OrderEntity>().eq(OrderEntity::getOrderSn,orderSn));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByOrderSn(String orderSn) {
        if (StringUtils.isEmpty(orderSn)){
            return;
        }
        //删除订单
        this.remove(new LambdaQueryWrapper<OrderEntity>().eq(OrderEntity::getOrderSn,orderSn));
        //删除订单项
        orderItemService.remove(new LambdaQueryWrapper<OrderItemEntity>().eq(OrderItemEntity::getOrderSn,orderSn));
    }


    @Override
    public PayVo getOrderPayInfo(String orderSn) {

        OrderEntity orderEntity = this.getOne(new LambdaQueryWrapper<OrderEntity>().eq(OrderEntity::getOrderSn, orderSn));

        if (Objects.nonNull(orderEntity)&&orderEntity.getStatus()==OrderStatusEnum.CREATE_NEW.getCode()){

            PayVo payVo = new PayVo();
            payVo.setOut_trade_no(orderEntity.getOrderSn());
            payVo.setBody(orderEntity.getNote());
            List<OrderItemEntity> orderItems = orderItemService.list(new LambdaQueryWrapper<OrderItemEntity>().eq(OrderItemEntity::getOrderSn,orderSn));
            payVo.setSubject(orderItems.get(0).getSkuName());//订单标题,取第一个订单项的名字
            payVo.setTotal_amount(orderEntity.getPayAmount().setScale(2,BigDecimal.ROUND_UP).toString());
            return payVo;
        }
        return null;
    }

    /**
     * 处理支付宝异步通知结果
     * 1,改变订单状态
     * 2,保存支付流水记录
     * 3，调用远程服务清空购物车
     * @param vo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String handlePayResult(PayAsyncVo vo) {

        if (vo.getTrade_status().equals("TRADE_SUCCESS")||vo.getTrade_status().equals("TRADE_FINISHED ")){
            String orderSn = vo.getOut_trade_no();
            OrderEntity orderEntity = getOrderByOrderSn(orderSn);
            OrderEntity updateOrder = new OrderEntity();
            updateOrder.setId(orderEntity.getId());
            updateOrder.setPaymentTime(DateUtils.stringToDate(vo.getGmt_payment(),"yyyy-MM-dd HH:mm:ss"));
            updateOrder.setStatus(OrderStatusEnum.PAYED.getCode());
            this.updateById(updateOrder);
            //保存支付流水信息
            paymentInfoService.savePayMentInfo(vo);

            //todo 清空购物车
//            List<OrderItemEntity> orderItems= orderItemService.list(new LambdaQueryWrapper<OrderItemEntity>().eq(OrderItemEntity::getOrderSn, orderSn));
//
//            cartFeignService.clearCart(orderItems.stream().map(item->item.getSkuId()).collect(Collectors.toList()));

            return "success";
        }else {
            return "error";
        }

    }

    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrderTo) {

//        MemberRespDTO memberResp = OrderInterceptor.loginUserLocal.get();
        //1.创建订单
        OrderEntity orderEntity = new OrderEntity();

        orderEntity.setOrderSn(seckillOrderTo.getOrderSn());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setMemberId(seckillOrderTo.getMemberId().longValue());
        orderEntity.setCreateTime(new Date());
        BigDecimal multiply = seckillOrderTo.getSeckillPrice().multiply(new BigDecimal("" + seckillOrderTo.getNum()));
        //设置订单应付金额
        orderEntity.setPayAmount(multiply);

        //设置订单收货信息
        List<UserAddressVo> receiveAddress = memberFeignService.getReceiveAddress(seckillOrderTo.getMemberId().longValue());
        List<UserAddressVo> defAddr = receiveAddress.stream().filter(addr -> addr.getDefaultStatus() == 1).collect(Collectors.toList());
        orderEntity.setReceiverCity(defAddr.get(0).getCity());
        orderEntity.setReceiverDetailAddress(defAddr.get(0).getDetailAddress());
        orderEntity.setReceiverName(defAddr.get(0).getName());
        orderEntity.setReceiverProvince(defAddr.get(0).getProvince());
        orderEntity.setReceiverRegion(defAddr.get(0).getRegion());
        orderEntity.setReceiverPhone(defAddr.get(0).getPhone());

        this.save(orderEntity);
        //2创建订单项

        OrderItemEntity itemEntity = new OrderItemEntity();

        itemEntity.setOrderSn(seckillOrderTo.getOrderSn());
        //设置购买数量
        itemEntity.setSkuQuantity(seckillOrderTo.getNum());
        itemEntity.setSkuId(seckillOrderTo.getSkuId());
        itemEntity.setSkuPrice(seckillOrderTo.getSeckillPrice());

        //设置商品基本信息
        R res = productFeignService.getSkuInfoWithSaleAttr(seckillOrderTo.getSkuId());
        if (res.getCode() == 0){
            SkuInfoWithSaleAttrDTO data = res.getData("data", new TypeReference<SkuInfoWithSaleAttrDTO>() {});
            itemEntity.setSkuName(data.getSkuInfoDTO().getSkuName());
            itemEntity.setSkuPic(data.getSkuInfoDTO().getSkuDefaultImg());
            itemEntity.setSkuAttrsVals(StringUtils.collectionToDelimitedString(data.getSkuSaleAttrValues(),";"));
        }



        orderItemService.save(itemEntity);

        //发送mq消息
        try {
            log.info("库存锁定成功，给mq发送消息,已经创建好的订单时间：{}", LocalDateTime.now());
            rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",orderEntity);
        }catch (Exception e){
            //TODO 可能由于网络原因发送失败，将消息记录到数据库中，之后在定期扫描发送失败的消息，重新发送
            log.error("发送创建订单成功消息失败,{}",e);
        }

    }

    private void saveOrder(OrderCreateVo orderCreateVo) {

        OrderEntity order = orderCreateVo.getOrder();
        order.setModifyTime(new Date());
        this.save(order);
        List<OrderItemEntity> orderItems = orderCreateVo.getOrderItems();
        orderItemService.saveBatch(orderItems);

    }

    private OrderCreateVo createOrder() {

        OrderCreateVo orderCreateVo = new OrderCreateVo();
        //1.生成订单号
        String orderSn = IdWorker.getTimeId();
        //2.根据订单号创建订单
        OrderEntity order = buildOrder(orderSn);
        //3.创建所有的订单项
        List<OrderItemEntity> orderItems = buildOrderItems(orderSn);
        //4.计算价格
        computePrice(order,orderItems);
        orderCreateVo.setOrder(order);
        orderCreateVo.setOrderItems(orderItems);
        return orderCreateVo;

    }

    private void computePrice(OrderEntity order, List<OrderItemEntity> orderItems) {
        //订单总额
        BigDecimal totalAmount = new BigDecimal("0.0");
        //订单应付总额
        BigDecimal payAmount = new BigDecimal("0.0");
        //优惠总额，promotionAmount，integrationAmount，couponAmount
        BigDecimal promotionAmount = new BigDecimal("0.0");
        BigDecimal integrationAmount = new BigDecimal("0.0");
        BigDecimal couponAmount = new BigDecimal("0.0");
        //可获得的成长值，积分
        Integer integration= 0;
        Integer growth= 0;

        if (orderItems!=null&&orderItems.size()>0){
            for (OrderItemEntity orderItem : orderItems) {
                //叠加订单总额
                totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuQuantity().toString())));
                //叠加应付总额
                payAmount = payAmount.add(orderItem.getRealAmount());
                //叠加促销优化金额
                promotionAmount = promotionAmount.add(orderItem.getPromotionAmount());
                //叠加积分抵扣金额
                integrationAmount = integrationAmount.add(orderItem.getIntegrationAmount());
                //叠加优惠券抵扣金额
                couponAmount = couponAmount.add(orderItem.getCouponAmount());
                //叠加获得的成长值
                growth = growth + orderItem.getGiftGrowth();
                //叠加获得的积分
                integration = integration+orderItem.getGiftIntegration();
            }
        }

        //设置订单总额，应付总额，优惠总额，可获得的成长值，积分
        order.setTotalAmount(totalAmount);
        order.setPayAmount(payAmount.add(order.getFreightAmount()));//加上运费
        order.setPromotionAmount(promotionAmount);
        order.setIntegrationAmount(integrationAmount);
        order.setCouponAmount(couponAmount);
        order.setIntegration(integration);
        order.setGrowth(growth);
    }

    private List<OrderItemEntity> buildOrderItems(String orderSn) {

        //获取当前用户的所有购物项，最后一次查询商品的价格
        List<OrderConfirmItemVo> currentUserCartItem = cartFeignService.getCurrentUserCartItem();
        List<OrderItemEntity> orderItems = currentUserCartItem.stream().map(cartItem -> {
            OrderItemEntity orderItemEntity = buildOrderItem(cartItem);
            //这里可以不用设置订单id，因为订单号已经是唯一的了
            orderItemEntity.setOrderSn(orderSn);
            return orderItemEntity;
        }).collect(Collectors.toList());
        return orderItems;

    }

    private OrderItemEntity buildOrderItem(OrderConfirmItemVo cartItem) {

        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //1.设置订单信息，订单号
        //2.设置spu信息
        R result = productFeignService.getSpuInfoBySkuId(cartItem.getSkuId());
        SpuInfoVo data = result.getData("data", new TypeReference<SpuInfoVo>() {});
        orderItemEntity.setSpuName(data.getSpuName());//spu名称
        orderItemEntity.setSpuId(data.getId());//spuId
        orderItemEntity.setSpuBrand(data.getBrandName());//商品品牌名称
        orderItemEntity.setCategoryId(data.getCatalogId());//商品分类id
        //3.设置sku信息
        orderItemEntity.setSkuId(cartItem.getSkuId());//商品Id
        orderItemEntity.setSkuName(cartItem.getSkuTitle());//商品名字
        orderItemEntity.setSkuPic(cartItem.getSkuDefalutImg());//商品图片
        orderItemEntity.setSkuPrice(cartItem.getSkuPrice());//价格
        orderItemEntity.setSkuAttrsVals(StringUtils.collectionToDelimitedString(cartItem.getSkuSaleAttrValues(),";"));//销售属性值
        orderItemEntity.setSkuQuantity(cartItem.getCountNum());//购买的数量
        //4.设置优惠信息 [不做]
        orderItemEntity.setCouponAmount(new BigDecimal("0.0"));
        orderItemEntity.setPromotionAmount(new BigDecimal("0.0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0.0"));
        //设置实际价格：购买的商品价格-优惠价格
        BigDecimal originPrice = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        orderItemEntity.setRealAmount(originPrice.subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getIntegrationAmount()));
        //5.设置赠送的会员成长值，积分,使用商品价格做为成长值和积分
        orderItemEntity.setGiftIntegration(cartItem.getSkuPrice().multiply(new BigDecimal(cartItem.getCountNum()+"")).intValue());
        orderItemEntity.setGiftGrowth(cartItem.getSkuPrice().multiply(new BigDecimal(cartItem.getCountNum()+"")).intValue());
        return orderItemEntity;

    }

    /**
     * 构造订单数据
     * @return
     */
    private OrderEntity buildOrder(String orderSn) {
        //获取当前用户信息
        MemberRespDTO memberRespVo = OrderInterceptor.loginUserLocal.get();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        //设置会员信息
        orderEntity.setMemberId(memberRespVo.getId());
        orderEntity.setMemberUsername(memberRespVo.getUsername());
        //订单状态，刚创建为待付款状态
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        //订单创建时间h
        orderEntity.setCreateTime(new Date());
        //获取收货地址,运费
        OrderSubmitVo orderSubmitVo = submitVoThreadLocal.get();
        //运费默认为0
        orderEntity.setFreightAmount(new BigDecimal("0"));
        UserAddressVo addressVo = memberFeignService.getAddrByAddrId(orderSubmitVo.getAddrId());

        //设置收货地址信息
        orderEntity.setReceiverName(addressVo.getName());//收货人姓名
        orderEntity.setReceiverRegion(addressVo.getRegion());//区域
        orderEntity.setReceiverCity(addressVo.getCity());//市
        orderEntity.setReceiverProvince(addressVo.getProvince());//省
        orderEntity.setReceiverPostCode(addressVo.getPostCode());//邮政编码
        orderEntity.setReceiverDetailAddress(addressVo.getDetailAddress());//详细地址
        orderEntity.setReceiverPhone(addressVo.getPhone());//收货人电话号码

        //订单备注
        orderEntity.setNote(orderSubmitVo.getOrderNote());

        return orderEntity;
    }


}